package ru.yermak.bookkeeping.account;

import ru.yermak.bookkeeping.model.Account;
import ru.yermak.bookkeeping.model.User;
import ru.yermak.bookkeeping.model.Group;
import ru.yermak.bookkeeping.model.Currency;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Order;

import javax.annotation.Resource;

/**
 * User: harrier
 * Date: Sep 9, 2008
 */
@Repository
public class HibernateAccountDao implements AccountDao {

    @Autowired
    private HibernateTemplate hibernateTemplate;

    public List<Account> getAccountsByUserId(Integer userId) {
        User user = (User) hibernateTemplate.load(User.class, userId);
        Group group = user.getGroup();
        List<Account> accounts = hibernateTemplate.findByCriteria(DetachedCriteria.forClass(Account.class)
                .add(Restrictions.eq("group", group))
                .addOrder(Order.asc("name")));
        hibernateTemplate.initialize(accounts);
        return accounts;
    }

    public Integer insertAccount(Account account) {
        return (Integer) hibernateTemplate.save(account);
    }

    public Account getById(Integer accountId) {
        return (Account) hibernateTemplate.load(Account.class, accountId);
    }


    public void updateAccount(Account account) {
        hibernateTemplate.persist(account);
    }

    public void removeAccount(Account account) {
        hibernateTemplate.delete(account);
    }
}
